0 1 0 0
1 1 1 0
0 1 1 0
0 0 1 0
0 1 0 0
¶ÔÓÚÉÏÊöÕâ¸ö¾ØÕó£¬ÎÒÃÇÈËÄÔÊÇÈçºÎµÚһʱ¼ä·¢ÏÖÖмäÄÇÛç 1 µÄÄØ£¿ÎÒ¾õµÃÓ¦¸ÃÓÐÏÂÃæÕâ¸ö¹ý³Ì:
_
0 1 0 0 | |_
1 1 1 0 |*|*|
0 1 1 0 |*|*|
---------------
0 0 1 0
0 1 0 0
Ê×ÏÈÒ»ÑÛÅųýµôÐéÏßÏÂÃæµÄ¿ÉÄÜÐÔ£¬¶øÉÏÃæµÄ²¿·Ö£¬Ôõô¿´ÔõôÏñÊÇ 114. Largest Rectangle in Histogram µÄͼ¡£ÏÔÈ»Èç¹û½«²ãÊýÀÛ¼Ó£¬Ôò³ÉÁË height Õâ¸ö vector ÁË¡£
0 3 2 0
Õâ¾ÍÍêÈ«³ÉÁË 114 ÌâµÄ½â´ðÁË¡£
ËùÒÔÕâµÀÌâ±È½Ï͵ÀÁµÄ·½·¨£¬ÊÇÖ±½ÓʹÓà 114 ÌâÀïµÄ largestRectangleArea ·½·¨¡£²¢¹¹½¨³ö height Õâ¸ö vector ¼´¿É¡£
´ó²¿·ÖͯЬºÍÎÒÒ»Ñù£¬Óöµ½ÕâµÀÌâµÄʱºò£¬»¹Ã»Óöµ½ 114, ÄÇôÁé¸ÐÓ¦¸Ã²»»áÄÇôͻȻ£¬³£¹æµÄ˼·Ӧ¸Ã»¹ÊÇ DP¡£
µ«¶ÔÓÚ DP, ÎÒÒ»Ö±¶¼Î´ÕÒµ½ºÜºÃµÄ½â¾ö·½°¸¡£Áô×÷Èպ󲹳䡣
#include <vector>
using std::vector;
#include <stack>
using std::stack;
#include <algorithm>
using std::max; using std::min;
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int max_area = 0, i = 0, size = height.size();
for (stack<int> stk; i<size || !stk.empty(); )
if (stk.empty() || (i != size && height[stk.top()] <= height[i])) stk.push(i++);
else {
int tp = stk.top(); stk.pop();
max_area = max(max_area, height[tp] * (stk.empty() ? i : i-stk.top()-1));
}
return max_area;
}
int maximalRectangle(vector<vector<char> > &matrix) {
if (matrix.empty()) return 0;
int max_area = 0;
vector<int> height(matrix[0].size(), 0);
for (size_t i=0; i<matrix.size(); ++i) {
for (size_t j=0; j<matrix[0].size(); ++j)
if (matrix[i][j] == '0') height[j] = 0;
else ++height[j];
max_area = max(max_area, largestRectangleArea(height));
}
return max_area;
}
};